package br.org.acessobrasil.portal.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.log4j.Logger;
/**
 * Ponte para o dataSource configurado do Spring
 * @author Fabio Issamu Oshiro
 *
 */
public class MySqlConnection {
	private static Logger logger = Logger.getLogger(MySqlConnection.class);
	private static Connection con;
	private static DataSource dataSource;
	
	
	
	private static DataSource dataSourceEda;
	private static final boolean DATASOURCE = true;
	public static final int EDA = 1;

	/**
	 * Abre uma nova conexao ou utiliza o datasource
	 * 
	 * @return con
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 */
	public static Connection getConnection() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
		if(DATASOURCE && dataSource!=null){
			return dataSource.getConnection();
		}else{
			return getOldConnection();
		}
	}
	
	private static Connection getOldConnection() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
		Class.forName(Messages.getString("hibernate.connection.driver_class")).newInstance(); //$NON-NLS-1$
		con = DriverManager.getConnection(Messages.getString("hibernate.connection.url"), Messages.getString("hibernate.connection.username"), Messages.getString("hibernate.connection.password")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
		return con;
	}
	
	public static DataSource getDataSource() {
		return dataSource;
	}
	
	/**
	 * Atribuido pelo applicationContext.xml
	 * @param dataSource
	 */
	public void setDataSource(DataSource dataSource) {
		MySqlConnection.dataSource = dataSource;
	}
	/**
	 * Atribuido pelo applicationContext.xml
	 * @param dataSource
	 */
	public void setDataSourceEda(DataSource dataSource){
		MySqlConnection.dataSourceEda = dataSource;
	}
	public static Connection getConnectionEda() throws SQLException {
		if(dataSourceEda!=null){
			return dataSourceEda.getConnection();
		}else{
			try{
				Class.forName(Messages.getString("hibernate.connection.driver_class")).newInstance(); //$NON-NLS-1$
				Connection con = DriverManager.getConnection("jdbc:hsqldb:file:/db/bn", Messages.getString("hibernate.connection.username"), Messages.getString("hibernate.connection.password")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
				return con;
			}catch(Exception e){
				logger.error("Erro ao conectar com EDA ", e);
			}
		}
		return null;
	}
}

